// Copyright 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// Copyright (c) 2025, Shanghai Iluvatar CoreX Semiconductor Co., Ltd.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "igie_model.h"
#include "triton/backend/backend_common.h"
#include "triton/common/triton_json.h"
#include "triton/common/logging.h"
#include "triton/common/triton_json.h"

namespace triton { namespace backend { namespace igie {

TRITONSERVER_Error*
ModelState::Create(TRITONBACKEND_Model* triton_model, ModelState** state)
{

  LOG_VERBOSE(2) << "ModelState::Create()";

  try {
    *state = new ModelState(triton_model);
  }
  catch (const BackendModelException& ex) {
    RETURN_ERROR_IF_TRUE(
        ex.err_ == nullptr, TRITONSERVER_ERROR_INTERNAL,
        std::string("unexpected nullptr in BackendModelException"));
    RETURN_IF_ERROR(ex.err_);
  }

  // step1: get model configuration, and convert it to json style.
  (*state)->ParseModelConfig();

  // step2: get model repo path
  const char* location;
  TRITONBACKEND_ArtifactType type;

  TRITONBACKEND_ModelRepository(triton_model, &type, &location);
  std::string model_repository_path(location);

  // step3: get model version
  uint64_t version;
  RETURN_IF_ERROR(TRITONBACKEND_ModelVersion(triton_model, &version));

  // step4: get pre-built model engine according to model path + version
  // we will get the key-values likes {model_name - model_path} by calling ModelPaths().
  std::unordered_map<std::string, std::string> model_paths;
  ModelPaths(model_repository_path, version, false, false, &model_paths);

  if (model_paths.size() > 1)
  {
    LOG_MESSAGE(TRITONSERVER_LOG_ERROR, "!!! Only support 1 engine Per Model now!");
  }

  // step5: update loaded_models key-value map, and load pre-built engine.
  std::string model_path;
  for (auto iter = model_paths.begin(); iter != model_paths.end(); ++iter) {
    LOG_MESSAGE(TRITONSERVER_LOG_INFO, (std::string("TRITONBACKEND_ModelInitialize: scanning ") + iter->second).c_str());
    // update model file name
    (*state)->model_config_.SetStringObject("default_model_filename", iter->first);
  }

  // show update model config.
  triton::common::TritonJson::WriteBuffer buffer;
  (*state)->model_config_.Write(&buffer);
  LOG_MESSAGE(TRITONSERVER_LOG_INFO, buffer.Base());

  return nullptr;  // success
}

}}}  // namespace triton::backend::igie